package hgin

import (
	"github.com/gin-gonic/gin"
	"github.com/mosongcc/gotool/gjwt"
	"net/http"
	"strings"
	"time"
	"vitepress-serve/internal/common/errs"
)

const sessionContextKey = "session_context_token_key"
const jwt_cookie_key = "mss"
const jwt_secret = "jwtsecret"

type Token struct {
	Uid  string `json:"uid"`
	Type string `json:"type"`
}

// MiddlewareCookieJwt 会话验证
func MiddlewareCookieJwt(ctx *gin.Context) {
	t, err := GetCookieToken(ctx)
	if err != nil {
		_ = ctx.Error(err)
		ctx.Abort()
	}
	ctx.Set(sessionContextKey, t)
	ctx.Next()
}

func GetHeaderToken(ctx *gin.Context) (t Token, err error) {
	token := ctx.GetHeader("token")
	if token == "" {
		token, err = ctx.Cookie(jwt_cookie_key)
		if err != nil || token == "" {
			err = errs.E99910
		}
		return
	}
	t, err = gjwt.Decode[Token](token, jwt_secret)
	if err != nil {
		err = errs.E99910
		return
	}
	return
}

func GetCookieToken(ctx *gin.Context) (t Token, err error) {
	val, err := ctx.Cookie(jwt_cookie_key)
	if err != nil || val == "" {
		err = errs.E99910
		return
	}
	t, err = gjwt.Decode[Token](val, jwt_secret)
	if err != nil {
		err = errs.E99910
		return
	}
	return
}

// CtxToken 读取会话
func CtxToken(ctx *gin.Context) (v Token) {
	if value, exists := ctx.Get(sessionContextKey); exists {
		return value.(Token)
	}
	return
}

// GenToken 生成Token
func GenToken(v Token, expTime time.Time) string {
	return gjwt.Encode(v, expTime, jwt_secret)
}

func SetJwtCookie(ctx *gin.Context, value string, maxAge int) {
	domain := ctx.Request.Host
	hostArr := strings.Split(ctx.Request.Host, ".")
	if len(hostArr) > 2 {
		domain = "." + strings.Join(hostArr[len(hostArr)-2:], ".") //.mosong.cc
	}
	ctx.SetSameSite(http.SameSiteNoneMode) //跨站使用cookie
	ctx.SetCookie(jwt_cookie_key, value, maxAge, "/vpapi/", domain, true, true)
}
